<?php

namespace app\controller;

use app\exception\HttpResponseException;
use app\service\ProductionInfoReportService;
use app\service\TaskService;
use support\Request;
use support\Response;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;

class TaskController
{
    /**
     * @var TaskService
     */
    private $taskService;
    private $productionInfoReportService;

    public function __construct()
    {
        $this->taskService = TaskService::getInstance();
        $this->productionInfoReportService = ProductionInfoReportService::getInstance();
    }


    /**
     * 用户统计详情
     * @param Request $request
     * @return Response
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     * @throws HttpResponseException
     */
    public function userCountDetail(Request $request): Response
    {
        $param = $request->post();
        $res = $this->taskService->userCountDetail($param);
        return json(success_response('', $res));
    }

    /**
     * 获取该集下的任务统计
     * @param Request $request
     * @return Response
     */
    public function getEpisodeTaskStepCategoryProgressData(Request $request): Response
    {
        $param = $request->post();
        $stepCategoryIds = $param['step_category_ids'];
        $episodeId = $param['episode_id'];
        $projectId = $param['project_id'];
        $res = $this->taskService->getEpisodeTaskStepCategoryProgressData($stepCategoryIds, $episodeId, $projectId);
        return json(success_response('', $res));
    }

    /**
     * 获取会议列表
     * @param Request $request
     * @return Response
     */
    public function getMeetingList(Request $request): Response
    {
        $param = $request->post();
        $stepCategoryIds = $param['step_category_ids'];
        $episodeId = $param['episode_id'];
        $projectId = $param['project_id'];
        $res = $this->taskService->getMeetingList($stepCategoryIds, $episodeId, $projectId);
        return json(success_response('', $res));
    }

    /**
     * 获取排期最大结束时间
     * @param Request $request
     * @return Response
     */
    public function getPlanMaxEndTime(Request $request): Response
    {
        $param = $request->post();
        $episodeId = $param['episode_id'];
        $projectId = $param['project_id'];
        $res = $this->taskService->getPlanMaxEndTime($projectId, $episodeId);
        return json(success_response('', $res));
    }


    /**
     * 获取剧集计划封板时间
     * @param Request $request
     * @return Response
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function getEpisodePlanSealTime(Request $request): Response
    {
        $param = $request->post();
        $episodeId = $param['episode_id'];
        $projectId = $param['project_id'];
        $res = $this->taskService->getEpisodePlanSealTime($projectId, $episodeId);
        return json(success_response('', $res));
    }

    /**
     * 获取实际封板时间
     * @param Request $request
     * @return Response
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function getEpisodeSealTime(Request $request): Response
    {
        $param = $request->post();
        $episodeId = $param['episode_id'] ?? [];
        $res = $this->taskService->getEpisodeSealTime($episodeId);
        return json(success_response('', $res));
    }


    /**
     * 我负责的任务
     * @param Request $request
     * @return Response
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function myResponsibleTaskList(Request $request): Response
    {
        $param = $request->post();

        $projectId = $param['project_id'] ?? 0;
        $departmentId = $param['department_id'] ?? 0;
        $todoStepCategoryId = param_to_array($param['todo_step_category_id'] ?? '', ',', 'intval');
        $specialRoleFilter = $param['special_role_filter'] ?? '';
        $taskStepType = param_to_array($param['task_step_type'] ?? '');
        $executor = $param['executor'] ?? 0;
        $isMyResponsible = $param['is_my_responsible'] ?? 0; // TODO  check bool
        $executorUserIdList = param_to_array($param['executor_user_id_list'] ?? '', ',', 'intval');
        $dateType = $param['date_type'] ?? '';
        $onlyNotDone = $param['only_not_done'] ?? 0; // TODO check bool
        $standardOrOther = $param['standard_or_other'] ?? '';
        $startTime = $param['start_time'] ?? 0;
        $endTime = $param['end_time'] ?? 0;

        $searchName = $param['search_name'] ?? 0;
        $page = param_to_array($param['page'] ?? '', ',', 'intval');

        $res = $this->taskService->myResponsibleTaskList(
            $request,
            $projectId,
            $todoStepCategoryId,
            $startTime,
            $endTime,
            $taskStepType,
            $executor,
            $isMyResponsible,
            $departmentId,
            $executorUserIdList,
            $dateType,
            $onlyNotDone,
            $standardOrOther,
            $specialRoleFilter,
            $searchName,
            $page
        );
        return json(success_response('', $res));
    }


    /**
     * 我负责的任务
     * @param Request $request
     * @return Response
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function myResponsibleTaskCount(Request $request): Response
    {
        $param = $request->post();

        $projectId = $param['project_id'] ?? 0;
        $departmentId = $param['department_id'] ?? 0;
        $todoStepCategoryId = param_to_array($param['todo_step_category_id'] ?? '', ',', 'intval');
        $specialRoleFilter = $param['special_role_filter'] ?? '';
        $taskStepType = param_to_array($param['task_step_type'] ?? '');
        $executor = $param['executor'] ?? 0;
        $isMyResponsible = $param['is_my_responsible'] ?? 0; // TODO  check bool
        $executorUserIdList = param_to_array($param['executor_user_id_list'] ?? '', ',', 'intval');
        $dateType = $param['date_type'] ?? '';
        $onlyNotDone = $param['only_not_done'] ?? 0; // TODO check bool
        $standardOrOther = $param['standard_or_other'] ?? '';
        $startTime = $param['start_time'] ?? 0;
        $endTime = $param['end_time'] ?? 0;
        $searchName = $param['search_name'] ?? 0;
        $page = param_to_array($param['page'] ?? '', ',', 'intval');

        $res = $this->taskService->myResponsibleTaskCount(
            $request,
            $projectId,
            $specialRoleFilter,
            $todoStepCategoryId,
            $startTime,
            $endTime,
            $taskStepType,
            $executor,
            $isMyResponsible,
            $departmentId,
            $executorUserIdList,
            $dateType,
            $onlyNotDone,
            $standardOrOther,
            $searchName,
            $page);
        return json(success_response('', $res));
    }

    /**
     * 任务统计
     * @param Request $request
     * @return Response
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function count(Request $request): Response
    {
        $param = query_array_construct([
            'project_id' => 'intval',
            'department_id' => 'intval',
            'todo_step_category_id' => 'split_array|array_map,intval',
            'special_role_filter' => 'strval',
            'task_step_type' => 'split_array|array_map,strval',
            'task_status_code' => 'split_array|array_map,strval',
            'executor' => 'intval',
            'is_my_responsible' => 'strval',
            'executor_user_id_list' => 'split_array|array_map,intval',
            'date_type' => 'strval',
            'only_not_done' => 'strval',
            'standard_or_other' => 'strval',
            'start_time' => 'intval',
            'end_time' => 'intval',
            'history' => 'strval',
            'search_name' => 'strval',
        ], $request->post());

        $res = $this->taskService->count($request, $param);
        return json(success_response('', $res));
    }

    /**
     * 任务延期统计
     * @param Request $request
     * @return Response
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function delayCount(Request $request): Response
    {
        $param = query_array_construct([
            'project_id' => 'intval',          // 项目ID
            'department_id' => 'intval',       // 部门ID
            'todo_step_category_id_list' => 'split_array|array_map,intval',    // 环节ID 列表
            'todo_step_category_id' => 'split_array|array_map,intval',    // 环节ID 列表
            'start_time' => 'intval',
            'end_time' => 'intval',
            'query_range' => 'strval',
            'query_type' => 'strval',
        ], $request->post());

        $res = $this->taskService->delayCount(
            $request,
            $param
        );
        return json(success_response('', $res));
    }

    /**
     * 延期剧集列表
     * @param Request $request
     * @return Response
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function delayEpisodeList(Request $request): Response
    {
        $param = query_array_construct([
            'project_id' => 'intval',          // 项目ID
            'department_id' => 'intval',       // 部门ID
            'todo_step_category_id_list' => 'split_array|array_map,intval',    // 环节ID 列表
            'todo_step_category_id' => 'split_array|array_map,intval',    // 环节ID 列表
            'start_time' => 'intval',
            'end_time' => 'intval',
            'query_range' => 'strval',
            'query_type' => 'strval',
        ], $request->post());

        $res = $this->taskService->delayEpisodeList(
            $request,
            $param
        );
        return json(success_response('', $res));
    }


    /**
     * 人员列表
     * @origin TaskMyResponsible.UserList
     * @param Request $request
     * @return Response
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function userList(Request $request): Response
    {
        $param = $request->post();

        $projectId = $param['project_id'] ?? 0;
        $departmentId = $param['department_id'] ?? 0;
        $todoStepCategoryId = param_to_array($param['todo_step_category_id'] ?? '', ',', 'intval');
        $specialRoleFilter = $param['special_role_filter'] ?? '';
        $taskStepType = param_to_array($param['task_step_type'] ?? '');
        $executor = $param['executor'] ?? 0;
        $isMyResponsible = $param['is_my_responsible'] ?? 0; // TODO  check bool
        $executorUserIdList = param_to_array($param['executor_user_id_list'] ?? '', ',', 'intval');
        $dateType = $param['date_type'] ?? '';
        $onlyNotDone = $param['only_not_done'] ?? 0; // TODO check bool
        $standardOrOther = $param['standard_or_other'] ?? '';
        $startTime = $param['start_time'] ?? 0;
        $endTime = $param['end_time'] ?? 0;
        $searchName = $param['search_name'] ?? 0;
        $page = param_to_array($param['page'] ?? '', ',', 'intval');

        $res = $this->taskService->userList(
            $request,
            $projectId,
            $specialRoleFilter,
            $todoStepCategoryId,
            $startTime,
            $endTime,
            $taskStepType,
            $executor,
            $isMyResponsible,
            $departmentId,
            $executorUserIdList,
            $dateType,
            $onlyNotDone,
            $standardOrOther,
            $searchName,
            $page);
        return json(success_response('', $res));
    }

    /**
     *生产信息简报
     * @param Request $request
     * @return Response
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function productionInfoReport(Request $request): Response
    {
        $param = query_array_construct([
            'project_id' => 'intval',          // 项目ID
            'department_id' => 'intval',       // 部门ID
            'todo_step_category_id' => 'split_array|array_map,intval',    // 环节ID 列表
            'start_time' => 'intval',
            'end_time' => 'intval',
        ], $request->post());

        $res = $this->productionInfoReportService->productionInfoReport($param['project_id'], $param['start_time'], $param['end_time'], $param['department_id'], $param['todo_step_category_id']);
        $episodeList = array_unique(array_column($res, 'episode_name'));
        $episodeWeekMap = [];
        $dayEpisodeMap = [];
        foreach ($episodeList as $episodeName) {
            foreach (get_month_day_list($param['start_time'], $param['end_time']) as $day) {
                $episodeWeekMap[$episodeName]['episode_name'] = $episodeName;
                $dayEpisodeMap[$episodeName][] = $day;
            }
        }
        $episodeWeekMap = array_sort_by($episodeWeekMap, 'episode_name');
        foreach ($res as $item) {
            foreach ($dayEpisodeMap[$item['episode_name']] as $day) {
                $nowDayTIme = strtotime($day);
                $week = date('w', strtotime($day)) == '0' ? 7 : date('w', strtotime($day));
                if (empty($episodeWeekMap[$item['episode_name']]['week' . $week])) {
                    $episodeWeekMap[$item['episode_name']]['week' . $week] = [];
                }
                if ($item['plan_start_time'] <= $nowDayTIme && $nowDayTIme <= $item['plan_end_time']) {
                    $episodeWeekMap[$item['episode_name']]['week' . $week][] = $item;
                }
            }
        }
        return json(success_response('', array_values($episodeWeekMap)));
    }
}
